package com.ciwong.epaper.util;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

import com.ciwong.epaper.modules.epaper.bean.ZipPackageInfo;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.utils.ThreadTask;
import com.ciwong.mobilelib.utils.ZipHelper;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadLargeFileListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.unisound.edu.oraleval.sdk.sep15.IOralEvalSDK;
import com.unisound.edu.oraleval.sdk.sep15.OralEvalSDKFactory;

import java.io.File;
import java.io.Serializable;
import java.util.List;

/**
 * Created by Administrator on 2017/7/27.
 */
public class ZipPackageUtils {

    private static final String TAG = "ZipPackageUtils";


    public static void checkHtmlFileNeedDownload(final Context context, final BaseCallBack baseCallBack) {

        //解压REGIST.zip到路径 报名系统
        ThreadTask.getInstance().executorOtherThread(new Runnable() {
            @Override
            public void run() {
                boolean isLoacalHtmlFileExit = true;
                String targetPath = null;
                File targetFile = null;
                File htmlFile = null;
                boolean isSuccess;
                isLoacalHtmlFileExit = true;

                for (int i = 0; i < 5; i++) {
                    switch (i) {
                        case 0:
                            //在线报名
                            targetPath = ESystem.getProjectFolderPath(context)
                                    + File.separator + ESystem.REGIST;
                            targetFile = new File(targetPath);
                            htmlFile = new File(targetPath + File.separator + "signUp" + ESystem.HTML_SUFFIX);
                            if (!targetFile.isDirectory() || !htmlFile.exists()) {
                                isLoacalHtmlFileExit = false;
                                CWLog.d(TAG, "####### !isLoacalHtmlFileExit test#####" + ESystem.REGIST);
                            }
                            break;
                        case 1:
                            //在线作答
                            targetPath = ESystem.getProjectFolderPath(context)
                                    + File.separator + ESystem.ONLINE_PAPER;
                            targetFile = new File(targetPath);
                            htmlFile = new File(targetPath + File.separator + "paper" + ESystem.HTML_SUFFIX);
                            if (!targetFile.isDirectory() || !htmlFile.exists()) {
                                isLoacalHtmlFileExit = false;
                                CWLog.d(TAG, "####### !isLoacalHtmlFileExit test#####" + ESystem.ONLINE_PAPER);
                            }
                            break;
                        case 2:
                            //新视频讲解
                            targetPath = ESystem.getProjectFolderPath(context) + File.separator + ESystem.NEWVIEDO;
                            targetFile = new File(targetPath);
                            htmlFile = new File(targetPath + File.separator + "newVideo" + ESystem.HTML_SUFFIX);
                            if (!targetFile.isDirectory() || !htmlFile.exists()) {
                                isLoacalHtmlFileExit = false;
                                CWLog.d(TAG, "####### !isLoacalHtmlFileExit test#####" + ESystem.NEWVIEDO);
                            }
                            break;
                        case 3:
                            //听说模考
                            targetPath = ESystem.getProjectFolderPath(context) + File.separator + ESystem.LISTENSPEAKREDO;
                            targetFile = new File(targetPath);
                            htmlFile = new File(targetPath + File.separator + "lsReform" + ESystem.HTML_SUFFIX);
                            if (!targetFile.isDirectory() || !htmlFile.exists()) {
                                isLoacalHtmlFileExit = false;
                                CWLog.d(TAG, "####### !isLoacalHtmlFileExit test#####" + ESystem.LISTENSPEAK);
                            }
                            break;
                        case 4:
                            //互动教程
                            targetPath = ESystem.getProjectFolderPath(context) + File.separator + ESystem.Interactive_Tutorial;
                            targetFile = new File(targetPath);
                            htmlFile = new File(targetPath + File.separator + "itPaper" + ESystem.HTML_SUFFIX);
                            if (!targetFile.isDirectory() || !htmlFile.exists()) {
                                isLoacalHtmlFileExit = false;
                                CWLog.d(TAG, "####### !isLoacalHtmlFileExit test#####" + ESystem.Interactive_Tutorial);
                            }
                            break;
                    }
                }


                //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
                targetPath = ESystem.getProjectFolderPath(context)
                        + File.separator + ESystem.TEST + ".mp3";
                targetFile = new File(targetPath);

                if (targetFile.exists()) {
                    targetFile.delete();
                }
                isSuccess = FileUtil.copyFile(context, ESystem.TEST + ".mp3", targetFile);
                //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
                if (isLoacalHtmlFileExit && baseCallBack != null) {
                    CWLog.d(TAG, "#######isLoacalHtmlFileExit && baseCallBack!=null#####");
                    baseCallBack.success(true);
                    return;
                }

                //ListenSpeak从app内的包解压
                targetPath = ESystem.getProjectFolderPath(context) + File.separator + ESystem.LISTENSPEAK + ".zip";
                targetFile = new File(targetPath);
                if (targetFile.exists()) {
                    targetFile.delete();
                }
                isSuccess = FileUtil.copyFile(context, ESystem.LISTENSPEAK + ".zip", targetFile);
                CWLog.d("debug", "copy LISTENSPEAK " + isSuccess);
                if (isSuccess) {
                    isSuccess = ZipHelper.getInstance().addToUpZipTask(
                            targetPath, ESystem.getProjectFolderPath(context));
                    CWLog.d("debug", "unzip LISTENSPEAK " + isSuccess);
                }

                targetPath = ESystem.getProjectFolderPath(context)
                        + File.separator + ESystem.HTML;
                targetFile = new File(targetPath);
                if (!targetFile.isDirectory()) {
                    targetPath = ESystem.getProjectFolderPath(context)
                            + File.separator + ESystem.HTML + ".zip";
                    targetFile = new File(targetPath);
                    if (targetFile.exists()) {
                        targetFile.delete();
                    }

                    isSuccess = FileUtil.copyFile(context, ESystem.HTML + ".zip", targetFile);
                    CWLog.d("debug", "copy html " + isSuccess);
                    if (isSuccess) {
                        isSuccess = ZipHelper.getInstance().addToUpZipTask(
                                targetPath, ESystem.getProjectFolderPath(context));
                        CWLog.d("debug", "unzip VIEDO " + isSuccess);
                    }
                }


                //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

                targetPath = ESystem.getProjectFolderPath(context)
                        + File.separator + ESystem.VIDEO;
                targetFile = new File(targetPath);
                if (!targetFile.isDirectory()) {
                    targetPath = ESystem.getProjectFolderPath(context)
                            + File.separator + ESystem.VIDEO + ".zip";
                    targetFile = new File(targetPath);
                    if (targetFile.exists()) {
                        targetFile.delete();
                    }
                    isSuccess = FileUtil.copyFile(context, ESystem.VIDEO + ".zip", targetFile);
                    CWLog.d("debug", "copy html " + isSuccess);
                    if (isSuccess) {
                        isSuccess = ZipHelper.getInstance().addToUpZipTask(
                                targetPath, ESystem.getProjectFolderPath(context));
                        CWLog.d("debug", "unzip VIEDO " + isSuccess);
                    }
                }


                final boolean isExit = isLoacalHtmlFileExit;

                SerializableManager.getInstance().deSerialize(SerializableManager.SerializeKey.SHARE_KEY_ZIP_PACKAGE_LIST_INFO,
                        new BaseCallBack() {
                            @Override
                            public void success(Object data) {
                                if (data != null) {
                                    List<ZipPackageInfo> list = (List<ZipPackageInfo>) data;
                                    getZipUpdateInfo(context, list, !isExit, baseCallBack);
                                }
                            }

                            @Override
                            public void failed(int errorCode, Object data) {
                                getZipUpdateInfo(context, null, true, baseCallBack);
                            }

                            @Override
                            public void failed(Object data) {
                                getZipUpdateInfo(context, null, true, baseCallBack);
                            }
                        });
            }
        }, ThreadTask.ThreadPeriod.PERIOD_LOW);
    }


    public static void getZipUpdateInfo(final Context context, final List<ZipPackageInfo> compareList, final boolean isMustDownload, final BaseCallBack baseCallBack) {

        int versionCode = getAPPVersionCode(context);

        EpaperDao.getInstance().getZipPackageUpdateInfo(String.valueOf(versionCode), new BaseCallBack() {

            @Override
            public void success(Object data) {
                super.success(data);

                List<ZipPackageInfo> zipPackageInfoList = (List<ZipPackageInfo>) data;
                CWLog.d("MainActivity", "#####getZipUpdateInfo success########");
                if (null != zipPackageInfoList && zipPackageInfoList.size() > 0) {
                    CWLog.d("MainActivity", "#####getZipUpdateInfo success########" + zipPackageInfoList.size());
                    if (isMustDownload) {
                        for (int i = 0; i < zipPackageInfoList.size(); i++) {

                            ZipPackageInfo zipPackageInfo = zipPackageInfoList.get(i);
                            String filePath = ESystem.getDeleteTargetPath(zipPackageInfo);
                            File file = new File(filePath);
                            if (file.isDirectory()) {
                                try {
                                    FileUtil.deleteDir(file);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }


                            startFileDownload(context, zipPackageInfo, ESystem.getProjectFolderPath(context)
                                    + File.separator + zipPackageInfo.getRepoName() + ".zip", i == (zipPackageInfoList.size() - 1), baseCallBack);
                        }


                    } else {
//                        比较是否下载解压
                        for (ZipPackageInfo newPack : zipPackageInfoList) {

                            for (ZipPackageInfo oldPack : compareList) {
                                if (oldPack.getRepoId() == newPack.getRepoId() && !oldPack.getDigest().equals(newPack.getDigest())) {

                                    String filePath = ESystem.getDeleteTargetPath(newPack);
                                    File file = new File(filePath);
                                    if (file.isDirectory()) {
                                        try {
                                            FileUtil.deleteDir(file);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                    startFileDownload(context, newPack, ESystem.getProjectFolderPath(context)
                                            + File.separator + newPack.getRepoName() + ".zip", true, baseCallBack);
                                }
                            }
                        }
                    }

                    SerializableManager.getInstance().serialize(
                            SerializableManager.SerializeKey.SHARE_KEY_ZIP_PACKAGE_LIST_INFO,
                            (Serializable) zipPackageInfoList);
                }
            }

            @Override
            public void failed(int errorCode, Object data) {

                CWLog.d("MainActivity", "#####getZipUpdateInfo failed########");
                failed(data);
            }

            @Override
            public void failed(Object data) {
                CWLog.d("MainActivity", "#####getZipUpdateInfo failed########");

                if (null != compareList) {
                    for (int i = 0; i < compareList.size(); i++) {
                        ZipPackageInfo zipPackageInfo = compareList.get(i);
                        String filePath = ESystem.getDeleteTargetPath(zipPackageInfo);
                        File file = new File(filePath);
                        if (file.isDirectory()) {
                            FileUtil.deleteDir(file);
                        }


                        startFileDownload(context, zipPackageInfo, ESystem.getProjectFolderPath(context)
                                + File.separator + zipPackageInfo.getRepoName() + ".zip", i == (compareList.size() - 1), baseCallBack);
                    }

                }
            }
        });
    }


    public static void startFileDownload(Context context, final ZipPackageInfo zipPackageInfo, final String savePath, final boolean lastOne, final BaseCallBack baseCallBack) {
        FileDownloader mFileDownloader = FileDownloader.getImpl();
        mFileDownloader.setMaxNetworkThreadCount(1);
        BaseDownloadTask task = mFileDownloader.create(zipPackageInfo.getUrl())
                .setPath(savePath)
                .setAutoRetryTimes(5)
                .setTag(zipPackageInfo)
                .setListener(new FileDownloadLargeFileListener() {
                    @Override
                    protected void pending(BaseDownloadTask task, long soFarBytes, long totalBytes) {


                    }

                    @Override
                    protected void progress(BaseDownloadTask task, long soFarBytes, long totalBytes) {


                    }

                    @Override
                    protected void paused(BaseDownloadTask task, long soFarBytes, long totalBytes) {

                    }

                    @Override
                    protected void completed(BaseDownloadTask task) {
                        CWLog.e(TAG, "########completed task.getTargetFilePath()#####" + task.getTargetFilePath());


                        String targetPath = ESystem.getUnZipTargetPath(zipPackageInfo);
                        File targetFile = new File(ESystem.getDeleteTargetPath(zipPackageInfo));
                        FileUtil.deleteDir(targetFile);

                        boolean isSuccess = ZipHelper.getInstance().addToUpZipTask(savePath, targetPath);

                        if (lastOne && null != baseCallBack && isSuccess) {
                            baseCallBack.success(true);
                        }

                    }


                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {
                        if (baseCallBack != null) {
                            baseCallBack.failed("离线包下载失败");
                        }

                    }

                    @Override
                    protected void warn(BaseDownloadTask task) {
                    }
                });
        task.start();

    }


    /**
     * 获取apk的版本号 currentVersionCode
     *
     * @param ctx
     * @return
     */
    public static int getAPPVersionCode(Context ctx) {
        int currentVersionCode = 0;
        PackageManager manager = ctx.getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(ctx.getPackageName(), 0);
            String appVersionName = info.versionName; // 版本名
            currentVersionCode = info.versionCode; // 版本号
            System.out.println(currentVersionCode + " " + appVersionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return currentVersionCode;
    }


//    public static boolean CheckListenSpeakIsExists() {
//        boolean isLoacalHtmlFileExit = true;
//
//        String targetPath = ESystem.getProjectFolderPath() + File.separator + ESystem.LISTENSPEAKREDO;
//        File targetFile = new File(targetPath);
//        File htmlFile = new File(targetPath + File.separator + "lsReform" + ESystem.HTML_SUFFIX);
//        if (!targetFile.isDirectory() || !htmlFile.exists()) {
//            isLoacalHtmlFileExit = false;
//        }
//        return isLoacalHtmlFileExit;
//    }
}
